package com.bugs.reptile;


import com.model.JobInfo;
import org.apache.http.client.HttpClient;
import org.assertj.core.util.Strings;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 前程无忧html解释器
 */
public class Job51Parser implements Parser {
    private Integer totalPage = null;
    private Integer currPage = 0;
//    @Override
//    public boolean hasNextPage(Html html) {
//        // 下一页是获取json
//        return true;
//        //return !Strings.isNullOrEmpty(nextPageUrl(html));
//    }

    @Override
    public boolean hasNextPage(Html html) {
        this.setTargetCount(html);
        this.setCurrCount(html);
        return currPage < totalPage;
    }

    @Override
    public String nextPageUrl(Html html, String url) {
        // TODO 按照网站规则，修改URL
        String result = url.replaceAll("\\d{1,4}.html", String.valueOf(++currPage)+".html");
        return result;
    }

    @Override
    public List<String> getDetailUrls(Html html) {
        System.out.println();
        // 这里网页是获取json再动态渲染，所以要解析json获取url
        List<String> urls = new ArrayList<>(50);
        String htmlText = html.get();
        Pattern pattern = Pattern.compile("\"job_href.{1,70},");
        Matcher matcher = pattern.matcher(htmlText);
        while(matcher.find()) {
            String url = matcher.group().trim().substring(12);
            url = url.substring(0, url.length() - 2).replace("\\", "");
            urls.add(url);
        }
        return urls;
    }

    // 设置最大分页数
    public void setTargetCount(Html html) {
        if(this.totalPage == null) {
            String htmlText = html.get();

            Pattern targetP = Pattern.compile("\"total_page.{1,10},");
            Pattern intP = Pattern.compile("[^0-9]");

            Matcher targetM = targetP.matcher(htmlText);
            if(targetM.find()) {
                String target = targetM.group().trim();
                totalPage = Integer.parseInt(intP.matcher(target).replaceAll("").trim());
            }
        }
    }

    public void setCurrCount(Html html) {
        String htmlText = html.get();
        Pattern targetP = Pattern.compile("\"curr_page.{1,10},");
        Pattern intP = Pattern.compile("[^0-9]");

        Matcher targetM = targetP.matcher(htmlText);
        if(targetM.find()) {
            String target = targetM.group().trim();
            int currNum = Integer.parseInt(intP.matcher(target).replaceAll("").trim());
            if(currPage < currNum) { currPage = currNum; }
        }
    }

    public static void main(String[] args){
        String url = "https://search.51job.com/list/030200,000000,0000,00,9,99,Java,2,1.html?lang=c&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare=";
        int nextPage = 30;
        String result = url.replaceAll("\\d{1,4}.html", String.valueOf(nextPage)+".html");
        System.out.println(url);
        System.out.println(result);
    }

    /**
     * 转换日期
     * @param str
     * @return
     */
    private LocalDate convertDate(String str) {
        String[] strs = str.split("-");
        LocalDate date = LocalDate.of(LocalDate.now().getYear(), Integer.parseInt(strs[0]), Integer.parseInt(strs[1].substring(0, 2)));
        if(date == null) {
            System.out.println(date);
        }
        return date;
    }

    /**
     * 转换成????-????元单位
     * @param str
     * @return
     */
    private float[] convertWage(String str) {
        // 对应 月 年 单位
        if(str.contains("/月")) {
            str = str.replace("/月", "");
            return convertMoney(str);
        }else if(str.contains("/年")) {
            str = str.replace("/年", "");
            float prices[] = convertMoney(str);
            prices[0] /= 12;
            prices[1] /= 12;
            return prices;
        }
        return null;
    }

    // 转换金额单位
    private float[] convertMoney(String str) {
        // 对应 千 万 单位
        // 0.8-1万/月
        // 6-8千/月
        float[] prices = new float[2];
        if(str.contains("万")) {
            String[] strs = str.replace("万", "").split("-");
            prices[0] = Float.parseFloat(strs[0]) * 10000;
            prices[1] = Float.parseFloat(strs[1]) * 10000;
        }else if(str.contains("千")) {
            String[] strs = str.replace("千", "").split("-");
            prices[0] = Float.parseFloat(strs[0]) * 1000;
            prices[1] = Float.parseFloat(strs[1]) * 1000;
        }
        return prices;
    }

    @Override
    public JobInfo convertJobInfo(Html html) {
        JobInfo jobInfo = new JobInfo();
        // 标题
        Selectable title = html.$("div.cn");
        Document titleDoc = Jsoup.parse(title.get());
        jobInfo.setRecruitTitle(trim(titleDoc.getElementsByTag("h1").text()));
        // 公司名
        jobInfo.setCompanyName(trim(titleDoc.getElementsByClass("catn").text()));
        // 换算月薪, 单位(元)
        jobInfo.setWage(trim(titleDoc.getElementsByTag("strong").text()));

        float[] wage = convertWage(jobInfo.getWage());
        jobInfo.setMinWage(wage[0]);
        jobInfo.setMaxWage(wage[1]);

        String[] titleInfos = titleDoc.getElementsByClass("ltype").get(0).text().split("[|]");
        //jobInfo.setExpRange(trim(titleInfos[1].trim()));
        jobInfo.setCity(trim(titleInfos[0]));
        // TODO 这里有问题
        for (int i = 1; i < titleInfos.length; i++) {
            String text = trim(titleInfos[i]);
            if(text.contains("经验")){                       // 要求
                jobInfo.setExpRange(text);
            }else if(text.contains("发布")) {                // 日期
                jobInfo.setReleaseDate(convertDate(text));
            }else if(text.contains("招")) {
                jobInfo.setRecruitmentNum(text);
            }else{
                if(jobInfo.getAcademicRequirements() == null) {
                    jobInfo.setAcademicRequirements(text);
                }
            }
        }

        // 福利标签
        jobInfo.setWelfareTip(titleDoc.getElementsByClass("t1").text().trim());

        // 公司信息
        Document companyInfoDoc = Jsoup.parse(html.$("div.tBorderTop_box").$("div.com_tag").get());
        Elements companyInfoEls = companyInfoDoc.getElementsByClass("at");
        jobInfo.setCompanyType(companyInfoEls.get(0).text());
        jobInfo.setScale(companyInfoEls.get(1).text());
        jobInfo.setIndustry(companyInfoEls.get(2).text());
        // 职位信息
        Document positionInfo = Jsoup.parse(html.$("div.job_msg").get());
        Elements msgs = positionInfo.getElementsByTag("p");
        List<String> msgList = new ArrayList<>(10);
        msgs.stream().forEach(msg -> msgList.add(msg.text()));
        jobInfo.setRecruitInfo(String.join("", msgList));
        // 关键字
        if(positionInfo.getElementsByClass("fp").size() >= 2) {
            String keyWordHtml = positionInfo.getElementsByClass("fp").get(1).html();
            Elements keyWordsEL = Jsoup.parse(keyWordHtml).getElementsByClass("el");
            jobInfo.setRecruitKeyWord(keyWordsEL.text());
        }
        // 公司信息
        jobInfo.setCompanyInfo(Jsoup.parse(html.$("div.tmsg").get()).text());
        // 上班地址
        Elements addrPEl = Jsoup.parse(html.$("div.bmsg").nodes().get(1).get())
                .getElementsByClass("fp");
        jobInfo.setWorkAddress(addrPEl.text().substring(5));
        //System.out.println(JSON.toJSONString(jobInfo));
        return jobInfo;
    }

}
